<template>
  <el-card>
    <el-form :model="formData" ref="vForm" :rules="rules" label-position="left" label-width="80px" size="medium"
      @submit.prevent>
      <el-row>
        <el-col :span="12" class="grid-cell">
          <div style="color:pink;">说明：目前支持学科和关键字条件筛选</div>
        </el-col>
        <el-col :span="12" class="grid-cell">
          <div class="static-content-item" style="float: right;">
            <el-button type="success" size="medium" :icon="Edit" @click="router.push('new')">新增试题</el-button>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <!-- 学科 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="学科" prop="subjectID">
            <el-select v-model="formData.subject" class="full-width-input" clearable @change="onChange">
              <el-option v-for="item in subjectOptions" :key="item.id" :label="item.subjectName" :value="item.id"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 二级目录 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="二级目录" prop="twoIndex">
            <el-select v-model="formData.twoIndex" class="full-width-input" clearable>
              <el-option v-for="(item, index) in twoIndexOptions" :key="index" :label="item.label" :value="item.value"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 标签 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="标签" prop="tags">
            <el-select v-model="formData.tags" class="full-width-input" clearable>
              <el-option v-for="(item, index) in tagsOptions" :key="index" :label="item.label" :value="item.value"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 关键字 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="关键字" prop="keyWord">
            <el-input v-model="formData.keyWord" type="text" clearable></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- 试题类型 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="试题类型" prop="testingTypes">
            <el-select v-model="formData.testingTypes" class="full-width-input" clearable>
              <el-option v-for="(item, index) in testingTypesOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 难度 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="难度" prop="difficulty">
            <el-select v-model="formData.difficulty" class="full-width-input" clearable>
              <el-option v-for="(item, index) in difficultyOptions" :key="index" :label="item.label" :value="item.value"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 方向 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="方向" prop="direction">
            <el-select v-model="formData.direction" class="full-width-input" clearable>
              <el-option v-for="(item, index) in directionOptions" :key="index" :label="item.label" :value="item.value"
                :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <!-- 录入人 -->
        <el-col :span="6" class="grid-cell">
          <el-form-item label="录入人" prop="enterPeople">
            <el-select v-model="formData.enterPeople" class="full-width-input" clearable>
              <el-option v-for="(item, index) in enterPeopleOptions" :key="index" :label="item.label"
                :value="item.value" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6" class="grid-cell">
          <el-form-item label="题目备注" prop="titleNotes">
            <el-input v-model="formData.titleNotes" type="text" clearable></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="grid-cell">
          <el-form-item label="企业简称" prop="shortName">
            <el-input v-model="formData.shortName" type="text" clearable></el-input>
          </el-form-item>
        </el-col>
        <!-- 地区下拉选择 -->
        <el-col :span="6" class="grid-cell">
          <!-- 省 -->
          <el-form-item label="城市" style="font-weight: 700;">
            <el-select v-model="formData.provinceList" class="m-2" clearable @change="onChangeProvince">
              <el-option v-for="(item, index) in provinceList" :key="index" :label="item.name" :value="item.province"
                :disabled="item.disabled" />
            </el-select>
            <!-- 市 -->
            <el-select v-model="formData.cityList" class="m-2" clearable>
              <el-option v-for="(item,index) in cityList" :key="index" :label="item.name" :value="item.code"
                :disabled="item.disabled" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" class="grid-cell">
          <div class="static-content-item">
            <el-button @click="onClear">清除</el-button>
            <el-button type="primary" size="medium" @click="onSearch">搜索</el-button>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <!-- 标签页 -->
    <el-tabs type="border-card" v-model="state" style="margin-top: 15px;" @tab-click="onTabClick">
      <el-alert :title="`数据一共${page.total}条`" type="info" show-icon :closable="false" />
      <el-tab-pane label="全部"> </el-tab-pane>
      <el-tab-pane label="待审核"> </el-tab-pane>
      <el-tab-pane label="已审核"> </el-tab-pane>
      <el-tab-pane label="已拒绝"> </el-tab-pane>
      <!-- 表格 -->
      <el-table style="width: 100%" :data="list">
        <el-table-column width="100" label="试题编号" prop="number">
        </el-table-column>
        <el-table-column prop="subject" label="学科" width="60"> </el-table-column>
        <el-table-column prop="catalog" label="目录" width="80"> </el-table-column>
        <el-table-column prop="questionType" label="题型" width="60">
          <template v-slot="{row}">
            <span v-if="row.questionType === '1'">单选</span>
            <span v-else-if="row.questionType === '2'">多选</span>
            <span v-else>简答</span>
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题干">
          <template v-slot="{row}">
            <span v-html="row.question"></span>
          </template>
        </el-table-column>
        <el-table-column prop="addDate" label="录入时间"> </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="60">
          <template v-slot="{row}">
            <span v-if="row.difficulty === '1'">简单</span>
            <span v-else-if="row.difficulty === '2'">一般</span>
            <span v-else>困难</span>
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" width="100"> </el-table-column>
        <el-table-column prop="chkState" label="审核状态" width="80">
          <template v-slot="{row}">
            <span v-if="row.chkState === 1">已审核</span>
            <span v-else-if="row.chkState === 2">已拒绝</span>
            <span v-else>待审核</span>
          </template>
        </el-table-column>
        <el-table-column prop="chkRemarks" label="审核意见"> </el-table-column>
        <el-table-column prop="chkUser" label="审核人" width="100"> </el-table-column>
        <el-table-column prop="publishState" label="发布状态" width="80">
          <template v-slot="{row}">
            <span v-if="row.publishState === 1">待发布</span>
            <span v-else-if="row.publishState === 2">已发布</span>
            <span v-else>已下架</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row}">
            <el-button @click="onShowDialogView(row)" type="primary" text>预览</el-button>
            <el-button @click="onShowDialongCheck(row)" :type="row.chkState !== 1 ? 'primary':'info'" text
              :disabled="row.chkState === 1">审核
            </el-button>
            <el-button type="primary" @click="router.push({path:'new', query: {id:row.id}})" text>修改</el-button>
            <el-button type="primary" @click="onLoad(row)" text>{{row.publishState === 1?'下架':'上架'}}
            </el-button>
            <el-button type="primary" @click="onDel(row)" text>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-row type="flex" justify="end">
        <el-pagination layout="total,prev, pager, next" :current-page="page.page" :page-size="page.pagesize"
          @current-change="onCurrentChange" :total="page.total">
        </el-pagination>
      </el-row>
    </el-tabs>
  </el-card>
  <!-- 审核 -->
  <el-dialog v-model="showDialongCheck" :title="title" width="20%" align-center>
    <CkeckDialog @close="showDialongCheck=false" @success="getList" ref="checkRef" v-if="showDialongCheck">
    </CkeckDialog>
  </el-dialog>
  <!-- 预览 -->
  <el-dialog v-model="showDialogView" :title="title" width="45%" align-center>
    <ViewDialog @close="showDialogView=false" @success="getList" ref="viewRef" v-if="showDialogView">
    </ViewDialog>
  </el-dialog>

</template>

<script>
import {
  defineComponent,
  toRefs,
  reactive,
  getCurrentInstance,
  onMounted,
  ref,
  nextTick
}
  from 'vue'
import { useRouter } from 'vue-router'
import { choice, choicePublish, remove } from '@/api/hmmm/questions.js'
import moment from 'moment'
import { list as subjectList } from '@/api/hmmm/subjects'
import { simple as simpleTwoIndex } from '@/api/hmmm/directorys'
import { simple as simpleTags } from '@/api/hmmm/tags'
import { direction } from '@/api/hmmm/constants'
import { Edit } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CkeckDialog from './components/ckeckDialog.vue'
import ViewDialog from './components/viewDialog.vue'
export default defineComponent({
  components: {
    CkeckDialog,
    ViewDialog
  },
  props: {},
  setup () {
    const router = useRouter()
    const formData = reactive({
      subjectID: undefined,
      twoIndex: undefined,
      tags: undefined,
      keyWord: undefined,
      testingTypes: undefined,
      difficulty: undefined,
      direction: undefined,
      enterPeople: undefined,
      titleNotes: undefined,
      shortName: undefined,
      // 省列表
      provinceList: undefined,
      // 市列表
      cityList: undefined
    })
    const state = reactive({
      subjectOptions: undefined,
      twoIndexOptions: undefined,
      tagsOptions: undefined,
      // 题型
      testingTypesOptions: [{
        label: '单选',
        value: 1
      }, {
        label: '多选',
        value: 2
      }, {
        label: '简答',
        value: 3
      }],
      // 难度
      difficultyOptions: [{
        label: '简单',
        value: 1
      }, {
        label: '一般',
        value: 2
      }, {
        label: '困难',
        value: 3
      }],
      // 方向
      directionOptions: [],
      // 录入人
      enterPeopleOptions: [{
        label: '录入管理员',
        value: 3
      }, {
        label: '超级管理员',
        value: 2
      }]

    })
    const list = ref([])
    const page = reactive({
      page: 1,
      pagesize: 5,
      total: undefined
    })
    const instance = getCurrentInstance()
    const showDialongCheck = ref(false)
    const showDialogView = ref(false)
    const checkRef = ref()
    const viewRef = ref()
    const title = ref(undefined)
    // 引入插件的省/市数据
    const { province, city } = require('province-city-china/data')
    state.provinceList = province
    state.cityList = city
    // 省选择市改变
    function onChangeProvince (val) {
      state.cityList = city.filter(item => item.province === val)
    }
    // 重置表单
    const submitForm = () => {
      instance.ctx.$refs.vForm.validate(valid => {
        if (!valid) return
        // TODO: 提交表单
        console.log(111)
      })
    }
    // 遍历方向
    direction.forEach((t, i) => {
      // state.directionOptions = []
      state.directionOptions.push({ label: t, value: i + 1 })
      // console.log(state.directionOptions)
    })
    // 初始化获取数据
    onMounted(() => {
      // 获取列表
      getList()
      // 获取学科列表
      getSubjectList()
      // 获取二级目录
      getTwoIndex()
      // 获取标签
      getTags()
    })
    // 获取列表
    async function getList () {
      const { data: { counts, items } } = await choice({
        ...page,
        ...formData
      })
      console.log({ counts, items })
      // 格式化时间
      items.forEach(t => {
        t.addDate = moment(t.addDate).format('YYYY-MM-DD HH:mm:ss')
      })
      page.total = counts
      list.value = items
    }
    // 获取学科列表
    async function getSubjectList () {
      // const res = await subjectList()
      // console.log(res)
      const { data: { items } } = await subjectList()
      state.subjectOptions = items
    }
    // 获取二级目录
    async function getTwoIndex (id) {
      const { data } = await simpleTwoIndex({ subjectID: id })
      state.twoIndexOptions = data
    }
    // 获取标签
    async function getTags (id) {
      const { data } = await simpleTags({ subjectID: id })
      state.tagsOptions = data
    }
    // 分页
    function onCurrentChange (val) {
      page.page = val
      getList()
    }
    // 学科选择改变
    function onChange (val) {
      formData.subjectID = val
      getTwoIndex(val)
      getTags(val)
    }
    // 重置表单
    const resetForm = () => {
      console.log(111)
      instance.ctx.$refs.vForm.resetFields()
    }
    // 清除
    function onClear () {
      Object.assign(state, {
        subjectOptions: undefined,
        twoIndexOptions: undefined,
        tagsOptions: undefined,
        testingTypesOptions: undefined,
        difficultyOptions: undefined,
        enterPeopleOptions: undefined,
        directionOptions: undefined
        // provinceList: undefined,
        // cityList: undefined
      })
      Object.assign(formData, {
        subjectID: undefined,
        twoIndex: undefined,
        tags: undefined,
        keyWord: undefined,
        testingTypes: undefined,
        difficulty: undefined,
        direction: undefined,
        enterPeople: undefined,
        titleNotes: undefined,
        shortName: undefined,
        provinceList: undefined,
        cityList: undefined
      })
      // state.provinceList = province
      // state.cityList = city
      onSearch()
    }
    // 查询
    function onSearch () {
      page.page = 1
      getList()
    }
    // 下/上架
    function onLoad (row) {
      ElMessageBox.confirm('确认删除？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if (row.publishState === 1) {
          row.publishState = 0
        } else {
          row.publishState = 1
        }
        choicePublish(row).then(() => {
          ElMessage.success('删除成功！')
          getList()
        })
      }).catch(() => {

      })
    }
    // 审核
    async function onShowDialongCheck (row) {
      title.value = '题目审核'
      showDialongCheck.value = true
      await nextTick()
      checkRef.value.form.id = row.id
      console.log(checkRef.value)
    }
    // 预览
    async function onShowDialogView (row) {
      title.value = '题目预览'
      showDialogView.value = true
      await nextTick()
      Object.assign(viewRef.value.form, row)
      // Object.assign(viewRef.value.data.id, row.id)
    }
    // 删除
    async function onDel (id) {
      console.log(id)
      await remove(id)
      getList()
    }
    return {
      ...toRefs(state),
      submitForm,
      resetForm,
      getList,
      page,
      list,
      onCurrentChange,
      getSubjectList,
      getTwoIndex,
      onChange,
      getTags,
      onChangeProvince,
      onClear,
      onSearch,
      formData,
      Edit,
      onLoad,
      showDialongCheck,
      onShowDialongCheck,
      title,
      onShowDialogView,
      showDialogView,
      checkRef,
      viewRef,
      onDel,
      router
    }
  }
})

</script>

<style lang="scss">
.el-input-number.full-width-input,
.el-cascader.full-width-input {
  width: 100% !important;
}

.el-form-item--medium {
  .el-radio {
    line-height: 36px !important;
  }

  .el-rate {
    margin-top: 8px;
  }
}

.el-form-item--small {
  .el-radio {
    line-height: 32px !important;
  }

  .el-rate {
    margin-top: 6px;
  }
}

.el-form-item--mini {
  .el-radio {
    line-height: 28px !important;
  }

  .el-rate {
    margin-top: 4px;
  }
}

.clear-fix:before,
.clear-fix:after {
  display: table;
  content: "";
}

.clear-fix:after {
  clear: both;
}

.float-right {
  float: right;
}
</style>

<style lang="scss" scoped>
// 自定义
::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
  padding-right: 22px;
}

.static-content-item {
  display: flex;
  justify-content: end;
  padding-right: 26px;
}

.el-row .el-select {
  width: 314px;
}

.el-row {
  height: 54px;
}

.el-alert {
  margin-bottom: 15px;
}

.el-row .el-input {
  width: 314px;
}

.el-table__cell .el-button {
  padding: 0;
  margin: 3px;
}

// 自定义
div.table-container {
  table.table-layout {
    width: 100%;
    table-layout: fixed;
    border-collapse: collapse;

    td.table-cell {
      display: table-cell;
      height: 36px;
      border: 1px solid #e1e2e3;
    }
  }
}

div.tab-container {}

.label-left-align :deep(.el-form-item__label) {
  text-align: left;
}

.label-center-align :deep(.el-form-item__label) {
  text-align: center;
}

.label-right-align :deep(.el-form-item__label) {
  text-align: right;
}

.custom-label {}

.static-content-item {
  min-height: 20px;
  display: flex;
  align-items: center;

  :deep(.el-divider--horizontal) {
    margin: 0;
  }
}
</style>
